package server;

import game.Player;

import java.util.Iterator;


import server.utils.CommandType;

public class Broadcaster extends Thread {
	private ActiveSessions activeSessions;
	private OutboundMessages outMessages;
	
	public Broadcaster(ActiveSessions activeSessions, OutboundMessages outMessages) {
		this.activeSessions = activeSessions;
		this.outMessages = outMessages;
		start();
	}

	@Override
	public void run() {
		while(true) {
			Message msg = outMessages.getMessage(); //blocked
			boolean toAll = false;
			if (msg.getTo() == null) {
				toAll = true;
			}
			synchronized (activeSessions) {
				Iterator<ClientSession> active = activeSessions.iterator();
				while(active.hasNext()) {
					ClientSession cli = active.next();
					if (cli.isAlive()) {
						if (toAll) {
							if (!cli.getName().equalsIgnoreCase(msg.getFrom())) {
								cli.sendMessage(msg);
							}
						} else if (msg.getTo().equalsIgnoreCase(cli.getName())){
							cli.sendMessage(msg);
							break;
						}
					} else {
						active.remove();
					}
				}
			}
		}
	}

	
	
}
